package com.lnkj.spcj.ui.scan

import android.view.MotionEvent
import android.view.WindowManager
import com.alibaba.fastjson.JSON
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.king.zxing.CaptureHelper
import com.king.zxing.OnCaptureCallback
import com.lnkj.spcj.R
import com.lnkj.spcj.base.BaseActivity2
import com.lnkj.spcj.net.Net
import com.lnkj.spcj.net.UrlUtils
import com.lnkj.spcj.ui.camera.CameraActivity
import com.lnkj.spcj.util.fromFastjsonToBean
import com.lnkj.spcj.util.utilcode.AppUtils
import com.lnkj.spcj.util.utilcode.BarUtils
import kotlinx.android.synthetic.main.activity_scan.*
import org.jetbrains.anko.startActivity


class ScanActivity : BaseActivity2(), OnCaptureCallback {
    override val layoutRes: Int
        get() = R.layout.activity_scan
    private var mCaptureHelper: CaptureHelper? = null

    override fun initAll() {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        BarUtils.setStatusBarAlpha(this)
        mCaptureHelper = CaptureHelper(this, surfaceView, viewfinderView, ivFlash)
        mCaptureHelper?.also {
            it.setOnCaptureCallback(this)
            it.onCreate()
            it.vibrate(true)
                    .fullScreenScan(true)//全屏扫码
                    .supportVerticalCode(true)//支持扫垂直条码，建议有此需求时才使用。
                    .supportLuminanceInvert(true)//是否支持识别反色码（黑白反色的码），增加识别率
                    .continuousScan(true)
        }

//        Observable.interval(1, TimeUnit.SECONDS).subscribe {
//            val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//            val info = manager.getRunningTasks(1)[0]
//            val shortClassName = info.topActivity.shortClassName //类名
//
//            val className = info.topActivity.className //完整类名
//
//            val packageName = info.topActivity.packageName //包名
//
//            LogUtils.eTag(TAG,packageName+":"+className)
//
//        }
    }

    override fun setListener() {
        iv_left.setOnClickListener {
            onBackPressed()
        }
    }

    override fun processLogic() {
        Net.post(mContext, UrlUtils().getBanBen, emptyMap(), object
            : Net.Callback() {
            override fun onSuccess(t: Any?) {
                runOnUiThread {
                    var versionBean = t?.fromFastjsonToBean<VersionBean>()
                    val code = AppUtils.getAppVersionCode()
                    val codeOnline = versionBean?.versionCode?.toDouble() ?: 0.00
                    if (codeOnline?.compareTo(code) > 0) {
                        AllenVersionChecker
                                .getInstance()
                                .downloadOnly(
                                        UIData.create()
                                                .setTitle("更新提示")
                                                .setContent(versionBean?.updateLog ?: "")
                                                .setDownloadUrl(versionBean?.downurl ?: "")
                                )
                                .setForceRedownload(true)
//                                .setForceUpdateListener { } //设置此监听会强制用户更新版本
                                .executeMission(mContext)
                    } else {
//                        ToastUtils.showShort("已是最新版本")
                    }
                }

            }

            override fun onError(apiException: Throwable?) {

            }
        })
    }

    override fun onResume() {
        super.onResume()
        mCaptureHelper?.onResume()
    }

    override fun onPause() {
        super.onPause()
        mCaptureHelper?.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mCaptureHelper?.onDestroy()
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        mCaptureHelper?.onTouchEvent(event)
        return super.onTouchEvent(event)
    }

    override fun onResultCallback(result: String?): Boolean {
//        {"status":1,"info":"\u5f55\u5165\u4e8c\u7ef4\u7801","data":{"company_id":"2","department_id":"1","station_id":"1"}}
        try {
            var bean=JSON.parseObject(result, ScanResultBean::class.java)
            startActivity<CameraActivity>("bean" to bean)
            finish()
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }
}